package top.maof.mfcoin.tx;

import lombok.Data;
import top.maof.mfcoin.algo.SecretUtil;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * 区块链账户
 *
 * @author 毛逢
 * @date 2021/11/11 15:05
 */
@Data
public class Wallet {
    // 地址
    private String address;

    // 私钥
    private PrivateKey aPrivate;

    // 公钥
    private PublicKey aPublic;

    public static final String ALGORITHM = "RSA";


    public Wallet() {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            this.aPrivate = keyPair.getPrivate();
            this.aPublic = keyPair.getPublic();
            // 将公钥的base64编码作为钱包地址
            byte[] publicEncoded = this.aPublic.getEncoded();
            byte[] addressHash = SecretUtil.digest(SecretUtil.DIGEST_ALGORITHM_SHA256, publicEncoded);
            this.address = Base64.getEncoder().encodeToString(addressHash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }



    public static PrivateKey privateKey(byte[] pk) {
        KeyFactory kf = null;
        PrivateKey privateKey = null;
        try {
            kf = KeyFactory.getInstance(ALGORITHM);
            privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(pk));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return privateKey;

    }

    public static PublicKey publicKey(byte[] pk) {
        KeyFactory kf = null;
        PublicKey publicKey = null;
        try {
            kf = KeyFactory.getInstance(ALGORITHM);
            publicKey = kf.generatePublic(new X509EncodedKeySpec(pk));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return publicKey;
    }


}
